package com.njtoyo.taxi.admin.service.marketing.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivityPrized;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivitySeckillRule;
import com.njtoyo.taxi.admin.mapper.master.enums.ActivityPrizedCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.ActivitySeckillRuleRoundUnit;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivityPrizedMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivitySeckillRuleMapper;
import com.njtoyo.taxi.admin.rest.presenter.marketing.seckill.RuleListPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.marketing.seckill.SetRuleWrapper;
import com.njtoyo.taxi.admin.service.marketing.SeckillRuleService;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@DS(Const.PRIMARY_DS)
public class SeckillRuleServiceImpl implements SeckillRuleService {

    @Autowired
    private ActivityPrizedMapper activityPrizedMapper;

    @Autowired
    private ActivitySeckillRuleMapper activitySeckillRuleMapper;

    @Override
    public RestResult setRule(Long activityId, SetRuleWrapper setRuleWrapper) {
        // 校验秒杀活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, activityId);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 判断活动状态
        if (!seckill.getIsOfflineUpdate()) {
            return RestResult.failed("需要将活动下线后再设置规则");
        }

        if (!setRuleWrapper.getIsCoverAllRegions() && Objects.isNull(setRuleWrapper.getRegionId())) {
            return RestResult.failed("需设置区域编号");
        }

        // 判断是否已经存在规则（同地区的规则只能存在一条，全地区性质的规则也只能存在一条）
        QueryWrapper<ActivitySeckillRule> ruleQueryWrapper = new QueryWrapper<>();
        ruleQueryWrapper.eq("activity_id", activityId)
                .eq("is_cover_all_regions", setRuleWrapper.getIsCoverAllRegions())
                .eq(!setRuleWrapper.getIsCoverAllRegions() && Objects.nonNull(setRuleWrapper.getRegionId()), "region_id", setRuleWrapper.getRegionId())
                .ne(Objects.nonNull(setRuleWrapper.getRuleId()), "id", setRuleWrapper.getRuleId());

        Integer ruleCount = activitySeckillRuleMapper.selectCount(ruleQueryWrapper);

        if (ruleCount > 0) {
            return RestResult.failed("已存在相同规则");
        }

        ActivitySeckillRule setData = CopyUtil.copy(setRuleWrapper, ActivitySeckillRule.class);

        setData.setActivityId(activityId);

        // 周
        if (ActivitySeckillRuleRoundUnit.week == setData.getRoundUnit() && (Objects.isNull(setData.getRoundStartNumber()) || Objects.isNull(setData.getRoundEndNumber()))) {
            return RestResult.failed("缺少每轮开始或结束数字");
        }

        // 日
        if (ActivitySeckillRuleRoundUnit.day == setData.getRoundUnit()) {
            setData.setRoundStartNumber(null);
            setData.setRoundEndNumber(null);
        }

        if (Objects.isNull(setRuleWrapper.getRuleId())) {
            // 新增
            Integer res = activitySeckillRuleMapper.insert(setData);
            return RestResult.success(res);
        } else {
            // 修改
            setData.setId(setRuleWrapper.getRuleId());
            Integer res = activitySeckillRuleMapper.updateById(setData);
            return RestResult.success(res);
        }
    }

    @Override
    public RestResult<List<RuleListPresenter>> getRule(Long activityId) {
        // 校验秒杀活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, activityId);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        List<RuleListPresenter> list = activitySeckillRuleMapper.getList(activityId);

        return RestResult.success(list);
    }

    @Override
    public RestResult deleteRule(Long activityId, Long ruleId) {
        // 校验秒杀活动是否存在
        ActivityPrized seckill = activityPrizedMapper.getActivityById(ActivityPrizedCategory.seckill, activityId);
        if (Objects.isNull(seckill)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        // 删除后，至少保留一条规则
        QueryWrapper<ActivitySeckillRule> ruleQueryWrapper = new QueryWrapper<>();
        ruleQueryWrapper.eq("activity_id", activityId)
                .ne("id", ruleId);

        Integer ruleCount = activitySeckillRuleMapper.selectCount(ruleQueryWrapper);

        if (ruleCount == 0) {
            return RestResult.failed("至少需要保留一条规则");
        }

        int res = activitySeckillRuleMapper.deleteById(ruleId);
        return RestResult.success(res);
    }
}
